<template>
    <div class="category">
        <el-button style="margin-bottom: 10px" @click="changeDialog(true)" type="primary">新增分类</el-button>
        <el-table :data="categoryList" style="width: 100%" row-key="id" border>
            <el-table-column prop="name" label="分类名称" sortable></el-table-column>
            <el-table-column label="分类级别">
                <template #default="scope">
                    {{ scope.row.pid == 0 ? '一级分类' : '二级分类' }}
                </template>
            </el-table-column>
            <el-table-column label="分类编号" width="100">
                <template #default="scope">
                    {{ scope.row.index }}
                </template>
            </el-table-column>
            <el-table-column label="分类图片">
                <template #default="scope">
                    <img :src="scope.row.picture" width="60" alt="">
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-button @click="editCategory(scope.row)" type="primary">编辑</el-button>
                    <el-button @click="deleteCategory(scope.row)" type="danger">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <el-dialog v-model="dialogVisible" :title="isAddCategory ? '新增分类' : '编辑分类'" width="500" :destroy-on-close="true">
        <el-form ref="categoryForm" :model="categoryData" :rules="rules" label-width="80px">
            <el-form-item label="分类名称" prop="name">
                <el-input placeholder="请输入分类名称" :maxLength="20" v-model.trim="categoryData.name" />
            </el-form-item>
            <el-form-item label="二级分类">
                <el-radio-group v-model="isSecondCategory" :disabled="!isAddCategory && categoryData.pid == 0">
                    <el-radio label="是" :value="1"></el-radio>
                    <el-radio label="否" :value="0"></el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item v-if="isSecondCategory" label="上级分类">
                <el-select v-model="categoryData.pid" placeholder="请选择上级分类名称">
                    <el-option v-for="item in categoryList" :label="item.name" :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item v-if="isSecondCategory" label="分类图片">
                <el-upload ref="uploadRef" :auto-upload="false" :on-change="handlePictureChange"
                    :on-error="handlePictureError">
                    <el-button type="primary">选择图片</el-button>
                    <template #tip>
                        <div class="el-upload__tip">
                            图片文件大小不能超过 500kb
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSubmit(isAddCategory)">提交</el-button>
                <el-button @click="changeDialog(true)">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import { getCategoryListService, addCategoryService, updateCategoryService, deleteCategoryService } from '@/apis/category'
import { uploadService } from '@/apis/upload'
const categoryList = ref([])
const dialogVisible = ref(false)
const isAddCategory = ref(true)
const isSecondCategory = ref()
const categoryData = ref({
    name: '',
    pid: '',
    picture: ''
})
const rules = {
    name: [
        { required: true, message: '请输入分类名称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ]
}
const changeDialog = (isAdd) => {
    isAddCategory.value = isAdd;
    categoryData.value = { name: '', pid: '', picture: '' };
    isSecondCategory.value = 0;
    dialogVisible.value = !dialogVisible.value;
}
const getCategoryList = async () => {
    let res = await getCategoryListService();
    // 处理数据
    let data = res.data.filter(item => {
        return item.pid == 0;
    })
    data.forEach(item => {
        item.children = res.data.filter(child => {
            return child.pid == item.id;
        });
    })
    categoryList.value = format(data);
}
const format = (items, parentIndex = '') => {
    let index = 1;
    return items.map((item, i) => {
        const currentIndex = parentIndex ? `${parentIndex}${i + 1}` : `${index++}`;
        const formattedItem = { ...item, index: currentIndex };
        if (item.children) {
            formattedItem.children = format(item.children, `${currentIndex}0`);
        }
        return formattedItem;
    });
};
const file = ref(null);
// 图片选择回调
const handlePictureChange = (uploadFile) => {
    file.value = uploadFile;
}
// 图片上传失败回调
const handlePictureError = (err) => {
    console.log('图片上传失败', err);
}
// 新增分类
const categoryForm = ref(null);
const handleSubmit = async (isAdd) => {
    categoryForm.value.validate(async (valid) => {
        if (!valid) {
            return false;
        }
        // 上传图片
        if (file.value) {
            let res = await uploadService(file.value.raw, 'category_picture');
            categoryData.value.picture = res.data.savepath;
        }
        categoryData.value.pid = categoryData.value.pid || 0;
        let res = await (isAdd ? addCategoryService(categoryData.value) : updateCategoryService(categoryData.value));
        changeDialog(true);
        getCategoryList();
        ElMessage.success(res.errmsg)
    });
}
// 编辑分类
const editCategory = (row) => {
    changeDialog(false);
    // 设置编辑数据
    categoryData.value = { id: row.id, name: row.name, pid: row.pid };
}
// 删除分类
const deleteCategory = (row) => {
    ElMessageBox.confirm('确认删除该分类吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        let params = {
            id: row.id
        }
        let res = await deleteCategoryService(params);
        getCategoryList();
        ElMessage.success(res.errmsg);
    }).catch(() => { });
}
// 页面加载时获取分类列表
getCategoryList();
</script>
<style scoped></style>